<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<%@page import="java.sql.Connection"%>
<%@page import="com.yuxin.common.util.DBUtil"%>
<%@page import="java.util.List"%>
<%@page import="java.util.Map"%>
<%@page import="java.util.regex.Pattern"%>
<%@page import="java.util.regex.Matcher"%>
<%@page import="com.yuxin.core.TransactionManager"%>
<%@page import="java.util.HashMap"%>
<%@page import="java.util.Date"%>
<%@page import="com.yuxin.common.util.FileUploadUtil"%>
<%@page import="java.util.Set"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.io.File"%>
<%@page import="com.yuxin.common.util.UUIDUtil"%>
<%@page import="com.yuxin.common.util.CommonUtil"%>

<%
	String action = request.getParameter("action"); // Request action parameter	
	Connection conn = null;
	TransactionManager tranM = null;
	String redirect = null;
	
	Map<String, Object> shopMap = new HashMap<String, Object>();
	String shop_id = null;
	String shop_name = null;
	String shop_img = null;
	try {
		conn = DBUtil.getConnection();
		Map<String,Object> user = (HashMap<String, Object>)request.getSession().getAttribute("user");
		String trade_id  = (String)user.get("SRC_ID");
		
		String sql = "select t.ID, t.NAME, t.IMG from p_shop t where t.TRADE_ID = ?";			
		shopMap = DBUtil.queryUniqueResult(conn, sql, trade_id);
		
		if(shopMap != null) {
			shop_id = shopMap.get("ID").toString();
			shop_name = shopMap.get("NAME").toString();
			shop_img = shopMap.get("IMG").toString();
		}
		
		if("setting".equals(action)) {				
			tranM = new TransactionManager(conn);
			tranM.begin();
			
			Map map =  FileUploadUtil.upload(request);
			Set set = map.entrySet();
			Iterator iter = set.iterator();
			String shopFile = "";
			Map<String, Object> formDataMap = null;
			
			while(iter.hasNext()) {
				Map.Entry entry = (Map.Entry) iter.next();
			    String key = entry.getKey().toString();
			    Object value = entry.getValue();
				if("files".equals(key)) {
					List<Map<String, Object>> uploadInfoList = (ArrayList<Map<String, Object>>)value; 	
					for(Map mapV : uploadInfoList) {
						String filed = mapV.get("filed").toString();
						if("shopFile".equals(filed)) {
							shopFile = mapV.get("path").toString();
						}
					}
				}
				if("formData".equals(key)) {
					formDataMap = (HashMap<String, Object>)value;
				}
			}					
			
			String shopname = formDataMap.get("shopname").toString();
			if(shopMap != null) {				
				if(shopFile != null && !"".equals(shopFile)) {
					sql = "update p_shop set NAME = ?, IMG = ?, UPDATE_TIME = ? where ID = ?";
					DBUtil.executeSql(conn, sql, new Object[]{shopname, shopFile, new Date(),shop_id});
					// Delete old picture
					String realpath = request.getSession().getServletContext().getRealPath("");
					String oldImg = shopMap.get("IMG").toString();
					File file = new File(realpath + oldImg.replace("/", File.separator));
					if(file.exists() && file.isFile()) {
						file.delete();
					}
				} else {
					sql = "update p_shop set NAME = ?, UPDATE_TIME = ? where ID = ?";
					DBUtil.executeSql(conn, sql, new Object[]{shopname, new Date(), shop_id});
				}
			} else {
				 sql = "insert into p_shop(ID, TRADE_ID, NAME, IMG, CREATE_TIME) values(?, ?, ?, ?, ?)";
				 DBUtil.executeSql(conn, sql, new Object[]{UUIDUtil.getUUID(), trade_id, shopname, shopFile, new Date()});
			}
			redirect = request.getContextPath()+"/trader/shopsetting.jsp";
		}
	} catch (Exception ex) {
		tranM.rollback();
		ex.printStackTrace();
	} finally {
		if(tranM != null) {
			tranM.commit();
		}	
		DBUtil.close(conn);
		if(redirect != null) {
			response.sendRedirect(redirect);
		}	
	}
%>
<!DOCTYPE html>
<html>
<head>
    <%@ include file="/meta.jsp" %>
    <title>${site_title}</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script language="javascript" type="text/javascript">
	<!--		
		function validateEle(id) {
			var obj = $("#" + id);
			if(obj.val() == "") {
				obj.addClass("error");
				obj.parent().parent().addClass("error");
				obj.focus();
				return false;	
			} else {
				obj.removeClass("error");
				obj.parent().parent().removeClass("error");
				return true;	
			}
		}
		
		$(document).ready(function(e) {
			$("#menu_shopsetting").addClass("active");	
           $("#submitBtn").bind("click", function(){
				if(!validateEle("shopname")) {
					return false;
				}
				if("<%=shop_id == null ? "" : shop_id %>" == "") {
					if($("#shopFile").val() == '') {
						$(".must-flag").html("请上传店招.");
						return false;	
					}
				}
				return true;		
			});
        });
	-->
 	</script>
</head>
<body>
<div class="zx-container" >
	<%@ include file="/trader/menu.jsp" %>
	<div class="span9 offset3">
		<%@ include file="/header_bg.jsp" %>
        <div class="row-fluid zx-bg-cont">
            <form id="shopForm" name="shopForm" method="post" action="shopsetting.jsp?action=setting" enctype="multipart/form-data" class="form-horizontal">                
                <div class="control-group">
                    <label class="control-label">店铺名称</label>
                    <div class="controls">
                        <input id="shopname" name="shopname" type="text" value="<%=shop_name != null ? shop_name : "" %>" 
                        	maxlength="100" onChange="validateEle('shopname');" />
                    </div>
                </div>
                 <div class="control-group">
                    <label class="control-label">店招</label>
                    <div class="controls">
                        <span style="display:none;" class="help-block">请选择2M以内的.jpg|.gif|.png文件</span>
                        <div style="overflow:hidden;">
                            <div id="img_preview" class="default-img left">
                                <img id="imgResShow" src="${ctx}/<%=shop_img != null ? shop_img : "images/default.png" %>">
                            </div>
                            <div id="del_btn" onclick="delImage(this);" class="left" style="cursor:pointer;z-index:1000;display:none;margin:-4px 0 0 -8px;">
                                <img align="absmiddle" title="删除图片" style="width:20px;height:20px;" src="${ctx}/images/close.png">
                            </div>
                        </div>
                        <a href="javascript:void(0);" rel="tooltip" data-original-title="请选择2M以内的.jpg|.gif|.png文件" class="input-file btn" 
                        	style="margin-left:30px; margin-top:5px;">
                            <input type="file" id="shopFile" name="shopFile" onchange="previewImage(this,'img_preview',100,80,imgPreview)"/>
                            <i class="icon icon-picture"></i> 选择图片
                        </a>
                      </div>
                    </div>
                 <div class="must-flag" style="text-align:center; display:block;"></div>
                 <div class="control-group">
                    <label class="control-label"></label>
                    <div class="controls">
                      <input id="submitBtn" type="submit" value="提交" style="width:100px; line-height:30px;" />
                    </div>
                </div>
            </form>
        </div>
		<%@ include file="/footer_bg.jsp" %>
	</div>
</div>
</body>
<script language="javascript" type="text/javascript">
	/**图片验证**/
    function imgPreview(){
        if($("#shopFile").validata("blankOrImage")){
            $("#del_btn").show();
            return true;
        }
    	return false;
    }
    /**图片删除**/
    function delImage(ele){
		$("#img_preview img").attr("src","${ctx}/images/default.png");
		$("#shopFile").val("");
		if("<%=shop_img %>" != '') {
			$("#img_preview img").attr("src","${ctx}/<%=shop_img %>");	
		}
		$(ele).hide();
    }
</script>
</html>